package com.taobaostore.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.taobaostore.common.ResponseCode;
import com.taobaostore.common.ServerResponse;
import com.taobaostore.dao.ReceiverMapper;
import com.taobaostore.pojo.Receiver;
import com.taobaostore.service.IReceiverService;
@Service
@Primary
public class ReceiverServiceImpl implements IReceiverService{
	@Autowired
	private ReceiverMapper receiverMapper;
	
	/**
	 * 新增收货地址记录
	 */
	public ServerResponse<String> add(Receiver receiver) {
		if (null == receiver) {
			return ServerResponse.createByError(ResponseCode.ILLEGAL_ARGUMENT.getCODE(), ResponseCode.ILLEGAL_ARGUMENT.getDESC());
		}
		int resultCount = receiverMapper.insert(receiver);
		if (resultCount == 1) {
			return ServerResponse.createBySuccess("新增地址成功!");
		}
		return ServerResponse.createByError("未知的错误请联系管理员");
	}

	/**
	 * 查询全部收货地址信息
	 * @param pageNum
	 * @param pageSize
	 * @param userId
	 * @return
	 */
	public ServerResponse<PageInfo<Receiver>> list(int pageNum,int pageSize,Integer userId){
		PageHelper.startPage(pageNum, pageSize);// 进行分页
		List<Receiver> receivers = Lists.newArrayList();
		if (null != userId) {
			receivers = receiverMapper.listReceiverByUserId(userId);
		}
		PageInfo<Receiver> pageInfo = new PageInfo<Receiver>(receivers);
		return ServerResponse.createBySuccess(pageInfo);
	}
	
	/**
	 * 删除指定收货地址
	 * @param receiverId
	 * @return
	 */
	public ServerResponse<String> delete(Integer userId,Integer receiverId){
		if (null == receiverId) {
			return ServerResponse.createByError(ResponseCode.ILLEGAL_ARGUMENT.getCODE(), ResponseCode.ILLEGAL_ARGUMENT.getDESC());
		}
		// 虽然我们已经有了地址表的id,但是为了防止横向越权还是要校验用户id
		int resultCount = receiverMapper.deleteReceiverById(userId,receiverId);
		if (resultCount == 1) {
			return ServerResponse.createBySuccess("删除地址成功!");
		}
		return ServerResponse.createByError("遇到未知问题,请联系管理员!");
	}
	
}